package com.iteaj.iot.boot.autoconfigure;

import com.iteaj.iot.taos.DefaultTaosSqlManager;
import com.iteaj.iot.taos.IotTaos;
import com.iteaj.iot.taos.TaosHandle;
import com.iteaj.iot.taos.TaosSqlManager;
import com.iteaj.iot.taos.proxy.TaosHandleProxyMatcher;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;

import javax.sql.DataSource;

/**
 * create time: 2022/1/18
 *
 * @author iteaj
 * @since 1.0
 */
@EnableScheduling
@EnableConfigurationProperties(IotTaosProperties.class)
@ConditionalOnClass(name = "com.iteaj.iot.taos.TaosSqlManager")
public class IotTaosAutoConfiguration {

    @Bean("taosDataSource")
    @ConditionalOnMissingBean(name = "taosDataSource")
    public Object taosDataSource(IotTaosProperties properties) {
        if(properties.getDatasource() == null) {
            throw new BeanCreationException("未配置数据源[iot.taos.datasource.xx]");
        }

        if(properties.getDatasource().getType() == null) {
            throw new BeanCreationException("未指定数据源类型[iot.taos.datasource.type]");
        }

        return IotTaos.databaseSource.taosDataSource = properties.getDatasource().build();
    }

    @Bean
    @ConditionalOnMissingBean(TaosSqlManager.class)
    public TaosSqlManager taosSqlManager(@Qualifier("taosDataSource") Object taosDataSource) {
        return new DefaultTaosSqlManager((DataSource) taosDataSource);
    }

    @Bean
    @Order(10000)
    @ConditionalOnBean(TaosHandle.class)
    @ConditionalOnMissingBean(TaosHandleProxyMatcher.class)
    public TaosHandleProxyMatcher taosHandleProxyMatcher(TaosSqlManager taosSqlManager) {
        return new TaosHandleProxyMatcher(taosSqlManager);
    }

}
